<?php

namespace app\admin\controller\crontab;

use app\admin\controller\AdminController;
use app\admin\service\crontab\CrontabService;
use app\admin\validate\crontab\CrontabValidate;
use think\response\Json;

/**
 * 定时任务控制器
 */
class Crontab extends AdminController
{
    /**
     * 定时任务列表
     * @return Json
     */
    public function lists()
    {
        return $this->data(CrontabService::getList());
    }


    /**
     * 添加定时任务
     * @return Json
     */
    public function add()
    {
        $params = (new CrontabValidate())->post()->checkParam('add');
        $result = CrontabService::add($params);
        if(true === $result) {
            return $this->success([],'添加成功');
        } else {
            return $this->error(CrontabService::getError());
        }
    }


    /**
     * 查看定时任务详情
     * @return Json
     */
    public function detail()
    {
        $params = (new CrontabValidate())->checkParam('detail');
        $result = CrontabService::detail($params);
        return $this->data($result);
    }


    /**
     * 编辑定时任务
     * @return Json
     */
    public function edit()
    {
        $params = (new CrontabValidate())->post()->checkParam('edit');
        $result = CrontabService::edit($params);
        if(true === $result) {
            return $this->success([],'编辑成功');
        } else {
            return $this->error(CrontabService::getError());
        }
    }


    /**
     * 删除定时任务
     * @return Json
     */
    public function delete()
    {
        $params = (new CrontabValidate())->delete()->checkParam('delete');
        $result = CrontabService::delete($params);
        if(true === $result) {
            return $this->success([],'删除成功');
        } else {
            return $this->error('删除失败');
        }
    }


    /**
     * 操作定时任务
     * @return Json
     */
    public function operate()
    {
        $params = (new CrontabValidate())->checkParam('operate');
        $result = CrontabService::operate($params);
        if(true === $result) {
            return $this->success([],'操作成功');
        } else {
            return $this->error(CrontabService::getError());
        }
    }


    /**
     * 获取规则执行时间
     * @return Json
     */
    public function expression()
    {
        $params = (new CrontabValidate())->get()->checkParam('expression');
        $result = CrontabService::expression($params['expression']);
        return $this->data($result?$result:[]);
    }
}